package com.xinruke.hostels.common.exception.handler;

import com.xinruke.hostels.common.exception.BizException;
import com.xinruke.hostels.common.vo.ResultVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName GlobalExceptionHandler
 * @CreateDate 2019/7/4
 * @Author FengXinQiang
 * @Version V1.0.0.0
 * @Decription 全局异常处理
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    Logger logger = LoggerFactory.getLogger(this.getClass());

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResultVO handle(Exception exception, HttpServletResponse response) {
        ResultVO resultVO = ResultVO.fail();

        if (exception instanceof MethodArgumentNotValidException) {
            logger.error("数据校验异常：", exception);

            MethodArgumentNotValidException methodArgumentNotValidException = (MethodArgumentNotValidException) exception;

            String message = methodArgumentNotValidException.getBindingResult().getFieldError().getDefaultMessage();
            resultVO.setMessage(message);
        } else if (exception instanceof BizException) {
            logger.error("业务异常", exception);

            BizException bizException = (BizException) exception;
            resultVO.setCode(bizException.getCode());
            resultVO.setMessage(bizException.getMessage());
        } else if (exception instanceof HttpMessageNotReadableException) {
            logger.error("json转换错误", exception);
            HttpMessageNotReadableException httpMessageNotReadableException = (HttpMessageNotReadableException) exception;
            logger.error("json转换错误" + httpMessageNotReadableException.getLocalizedMessage());
            resultVO.setMessage("数据转换错误");

        } else {
            logger.error("服务运行异常：", exception);

            resultVO.setMessage("服务运行异常");
        }
        return resultVO;
    }
}
